from flask import Blueprint, jsonify, request
from src.models.user import Location, CircleMember, User, db
from datetime import datetime, timedelta

location_bp = Blueprint('location', __name__)

@location_bp.route('/locations', methods=['POST'])
def update_location():
    """更新用户位置"""
    data = request.json
    user_id = data.get('user_id')
    circle_id = data.get('circle_id')
    latitude = data.get('latitude')
    longitude = data.get('longitude')
    accuracy = data.get('accuracy')
    
    if not all([user_id, circle_id, latitude, longitude]):
        return jsonify({'error': '用户ID、圈子ID、经纬度不能为空'}), 400
    
    # 检查用户是否是圈子成员
    member = CircleMember.query.filter_by(
        circle_id=circle_id,
        user_id=user_id,
        is_active=True
    ).first()
    
    if not member:
        return jsonify({'error': '您不是该圈子的成员'}), 403
    
    # 创建位置记录
    location = Location(
        user_id=user_id,
        circle_id=circle_id,
        latitude=latitude,
        longitude=longitude,
        accuracy=accuracy
    )
    db.session.add(location)
    
    # 更新用户最后活跃时间
    user = User.query.get(user_id)
    if user:
        user.last_active = datetime.utcnow()
    
    db.session.commit()
    
    return jsonify(location.to_dict()), 201

@location_bp.route('/circles/<int:circle_id>/locations', methods=['GET'])
def get_circle_locations(circle_id):
    """获取圈子内所有成员的最新位置"""
    user_id = request.args.get('user_id')
    
    if not user_id:
        return jsonify({'error': '用户ID不能为空'}), 400
    
    # 检查用户是否是圈子成员
    member = CircleMember.query.filter_by(
        circle_id=circle_id,
        user_id=user_id,
        is_active=True
    ).first()
    
    if not member:
        return jsonify({'error': '您不是该圈子的成员'}), 403
    
    # 获取圈子内所有活跃成员的最新位置
    # 使用子查询获取每个用户的最新位置
    subquery = db.session.query(
        Location.user_id,
        db.func.max(Location.timestamp).label('latest_timestamp')
    ).filter(
        Location.circle_id == circle_id
    ).group_by(Location.user_id).subquery()
    
    # 获取最新位置记录
    latest_locations = db.session.query(Location, User).join(User).join(
        subquery,
        db.and_(
            Location.user_id == subquery.c.user_id,
            Location.timestamp == subquery.c.latest_timestamp
        )
    ).filter(
        Location.circle_id == circle_id
    ).all()
    
    # 过滤掉超过30分钟的位置（认为用户离线）
    cutoff_time = datetime.utcnow() - timedelta(minutes=30)
    
    location_list = []
    for location, user in latest_locations:
        if location.timestamp >= cutoff_time:
            location_info = location.to_dict()
            location_info['user'] = {
                'id': user.id,
                'nickname': user.nickname,
                'avatar_url': user.avatar_url
            }
            location_list.append(location_info)
    
    return jsonify(location_list)

@location_bp.route('/users/<int:user_id>/locations', methods=['GET'])
def get_user_location_history(user_id):
    """获取用户位置历史（可选功能）"""
    circle_id = request.args.get('circle_id')
    limit = request.args.get('limit', 50, type=int)
    
    if not circle_id:
        return jsonify({'error': '圈子ID不能为空'}), 400
    
    # 检查请求者是否是圈子成员
    requester_id = request.args.get('requester_id')
    if requester_id:
        member = CircleMember.query.filter_by(
            circle_id=circle_id,
            user_id=requester_id,
            is_active=True
        ).first()
        
        if not member:
            return jsonify({'error': '您没有权限查看该信息'}), 403
    
    # 获取用户在指定圈子的位置历史
    locations = Location.query.filter_by(
        user_id=user_id,
        circle_id=circle_id
    ).order_by(Location.timestamp.desc()).limit(limit).all()
    
    return jsonify([location.to_dict() for location in locations])

@location_bp.route('/circles/<int:circle_id>/online-members', methods=['GET'])
def get_online_members(circle_id):
    """获取圈子内在线成员列表"""
    user_id = request.args.get('user_id')
    
    if not user_id:
        return jsonify({'error': '用户ID不能为空'}), 400
    
    # 检查用户是否是圈子成员
    member = CircleMember.query.filter_by(
        circle_id=circle_id,
        user_id=user_id,
        is_active=True
    ).first()
    
    if not member:
        return jsonify({'error': '您不是该圈子的成员'}), 403
    
    # 获取最近30分钟内有位置更新的成员
    cutoff_time = datetime.utcnow() - timedelta(minutes=30)
    
    online_members = db.session.query(User, Location.timestamp).join(
        Location, User.id == Location.user_id
    ).join(
        CircleMember, User.id == CircleMember.user_id
    ).filter(
        CircleMember.circle_id == circle_id,
        CircleMember.is_active == True,
        Location.circle_id == circle_id,
        Location.timestamp >= cutoff_time
    ).distinct().all()
    
    member_list = []
    for user, last_update in online_members:
        member_info = {
            'id': user.id,
            'nickname': user.nickname,
            'avatar_url': user.avatar_url,
            'last_update': last_update.isoformat() if last_update else None
        }
        member_list.append(member_info)
    
    return jsonify(member_list)

